package com.vayne.demo;

import com.vayne.bean.Lesson;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * @author xuerui.zhang
 * @since 2020/3/16 上午11:52
 */
public class BeanScopeDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(BeanScopeDemo.class);
        // 启动应用上下文
        applicationContext.refresh();
        lookBean(applicationContext);
        applicationContext.close();
    }

    private static void lookBean(AnnotationConfigApplicationContext applicationContext) {
        for (int i = 0; i < 3; i++) {
            Lesson singletonLesson = applicationContext.getBean("singletonLesson", Lesson.class);
            System.out.println("singleton: " + singletonLesson);
            Lesson prototypeLesson = applicationContext.getBean("prototypeLesson", Lesson.class);
            System.out.println("prototype: " + prototypeLesson);
        }
    }

    @Bean
    public Lesson singletonLesson() {
        return createLesson();
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Lesson prototypeLesson() {
        return createLesson();
    }

    public static Lesson createLesson() {
        Lesson lesson = new Lesson();
        lesson.setId(System.nanoTime() + "");
        return lesson;
    }
}
